package kr.hkit.androidcomplete02.ch12;

import java.util.ArrayList;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Ch12_ListlconText extends Activity {
	ArrayList<MyItem> arLists;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch12_listviewtest);
		
		arLists = new ArrayList<>();
		arLists.add(new MyItem(R.drawable.ic_launcher, "삼성 노트북"));
		arLists.add(new MyItem(R.drawable.btnexit, "LG 세탁기"));
		arLists.add(new MyItem(R.drawable.toycar, "대우 마티즈"));
		
		MyListAdapter adapter = new MyListAdapter();
		
		ListView listView = (ListView) findViewById(R.id.list);
		listView.setAdapter(adapter);
	}
	
	class MyListAdapter extends BaseAdapter{
		String TAG = "MyListAdapter";
		LayoutInflater infalte;
		
		public MyListAdapter() {
			infalte = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			Log.d(TAG, "getCount()");
			return arLists.size();
		}

		public Object getItem(int position) {
			Log.d(TAG, "getItem("+ position + ")");
			return arLists.get(position);
		}

		public long getItemId(int position) {
			Log.d(TAG, "getItemId("+ position + ")");
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Log.d(TAG, "getView("+ position + ")");
			final int pos = position;
			if (convertView == null){
				convertView = infalte.inflate(R.layout.ch12_icontext, parent, false);
			}
			ImageView img = (ImageView) convertView.findViewById(R.id.img);
			img.setImageResource(arLists.get(position).mIcon);
			
			TextView tv = (TextView) convertView.findViewById(R.id.text);
			tv.setText(arLists.get(position).mName);
			
			Button btn = (Button) convertView.findViewById(R.id.btn);
			btn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					String text = arLists.get(pos).mName + "를 주문합니다.";
					Toast.makeText(getApplication(), text, Toast.LENGTH_LONG).show();
				}
			});
			return convertView;
		}
		
	}
	
	class MyItem{
		int mIcon;
		String mName;
		public MyItem(int mIcon, String mName) {
			super();
			this.mIcon = mIcon;
			this.mName = mName;
		}
	}
}
